import React, { useRef, useState, useEffect } from 'react';
import { View, Text, TouchableOpacity, SafeAreaView, Image, Modal, TextInput, Alert, TouchableWithoutFeedback, Animated, ScrollView } from 'react-native';
import { WebView } from 'react-native-webview';
import { DatePicker, Toast } from '@ant-design/react-native';
import { styles } from './styles';
import { getAllDept, getRoomResourceGroupScheduler, searchWorkOrder, getAssignmentBatchOrderList, getAssignmentMesTaskList, getTaskInfo, submitAssignmentTask } from './api';

interface WorkOrderDispatchProps {
    onBackPress?: () => void;
}

export default function WorkOrderDispatch({ onBackPress }: WorkOrderDispatchProps) {
    const webViewRef = useRef<WebView>(null);
    const [isDeptModalVisible, setIsDeptModalVisible] = useState(false);
    const [deptSearchText, setDeptSearchText] = useState('');
    const [deptList, setDeptList] = useState<any[]>([]);
    const [selectedDept, setSelectedDept] = useState<any>(null);
    const [isLoading, setIsLoading] = useState(false);
    const [isTouchInterceptorActive, setIsTouchInterceptorActive] = useState(false);
    const [selectedTimeScale, setSelectedTimeScale] = useState('hour'); // 添加时间刻度状态
    const rotateAnim = useRef(new Animated.Value(0)).current;

    // 工单详情弹窗状态
    const [isTaskDetailVisible, setIsTaskDetailVisible] = useState(false);
    const [selectedTask, setSelectedTask] = useState<any>(null);

    // 资源详情卡片状态
    const [isResourceDetailVisible, setIsResourceDetailVisible] = useState(false);
    const [selectedResource, setSelectedResource] = useState<any>(null);

    // 工单选择下拉框状态
    const [isWorkOrderDropdownVisible, setIsWorkOrderDropdownVisible] = useState(false);
    const [workOrderSearchText, setWorkOrderSearchText] = useState('');
    const [workOrderList, setWorkOrderList] = useState<any[]>([]); // 工单列表数据
    const [selectedWorkOrder, setSelectedWorkOrder] = useState<any>(null); // 选中的工单
    const [isWorkOrderLoading, setIsWorkOrderLoading] = useState(false); // 工单搜索加载状态

    // 批次选择下拉框状态
    const [isBatchDropdownVisible, setIsBatchDropdownVisible] = useState(false);
    const [batchList, setBatchList] = useState<any[]>([]); // 批次列表数据
    const [selectedBatch, setSelectedBatch] = useState<any>(null); // 选中的批次
    const [isBatchLoading, setIsBatchLoading] = useState(false); // 批次加载状态

    // 工序列表状态
    const [processList, setProcessList] = useState<any[]>([]); // 工序列表数据
    const [isProcessLoading, setIsProcessLoading] = useState(false); // 工序加载状态

    // 工序详情状态
    const [selectedProcess, setSelectedProcess] = useState<any>(null); // 选中的工序
    const [processDetail, setProcessDetail] = useState<any>(null); // 工序详情数据
    const [isProcessDetailLoading, setIsProcessDetailLoading] = useState(false); // 工序详情加载状态

    // 派工信息状态
    const [workDeviceId, setWorkDeviceId] = useState<string | null>(null); // 派工设备ID
    const [workStationId, setWorkStationId] = useState<string | null>(null); // 派工工位ID
    const [workUserId, setWorkUserId] = useState<string | null>(null); // 派工人员ID
    const [workLineId, setWorkLineId] = useState<string | null>(null); // 派工产线ID
    const [workStartTime, setWorkStartTime] = useState<string | null>(null); // 派工开始时间
    const [workEndTime, setWorkEndTime] = useState<string | null>(null); // 派工结束时间

    // 时间选择器状态
    const [startTimePickerVisible, setStartTimePickerVisible] = useState(false);
    const [endTimePickerVisible, setEndTimePickerVisible] = useState(false);
    const [isTimePickerActive, setIsTimePickerActive] = useState(false); // 新增：时间选择器激活状态

    // 强制重新渲染状态
    const [forceUpdate, setForceUpdate] = useState(0);

    // 下拉框状态
    const [deviceDropdownVisible, setDeviceDropdownVisible] = useState(false);
    const [userDropdownVisible, setUserDropdownVisible] = useState(false);
    const [stationDropdownVisible, setStationDropdownVisible] = useState(false);
    const [lineDropdownVisible, setLineDropdownVisible] = useState(false);

    // 派工提交加载状态
    const [isSubmitting, setIsSubmitting] = useState(false);

    // 清除甘特图数据
    const clearGanttData = () => {
        const script = `
            if (window.handleReactNativeMessage) {
                window.handleReactNativeMessage({
                    type: 'clearGantt'
                });
            }
        `;
        webViewRef.current?.injectJavaScript(script);
    };

    // 清空派工信息
    const clearDispatchInfo = () => {
        // 清空工单选择
        setSelectedWorkOrder(null);
        setWorkOrderSearchText('');
        setWorkOrderList([]);

        // 清空批次选择
        setSelectedBatch(null);
        setBatchList([]);

        // 清空工序选择
        setSelectedProcess(null);
        setProcessDetail(null);
        setProcessList([]);

        // 清空派工信息
        setWorkDeviceId(null);
        setWorkStationId(null);
        setWorkUserId(null);
        setWorkLineId(null);
        setWorkStartTime(null);
        setWorkEndTime(null);

        // 清空下拉框状态
        setDeviceDropdownVisible(false);
        setUserDropdownVisible(false);
        setStationDropdownVisible(false);
        setLineDropdownVisible(false);

        // 重置旋转动画状态
        deviceDropdownRotate.setValue(0);
        userDropdownRotate.setValue(0);
        stationDropdownRotate.setValue(0);
        lineDropdownRotate.setValue(0);

        // 清空搜索文本
        setDeptSearchText('');
        setDeptList([]);

        // 重置加载状态
        setIsWorkOrderLoading(false);
        setIsBatchLoading(false);
        setIsProcessLoading(false);
        setIsProcessDetailLoading(false);

        // 重置时间选择器状态
        setStartTimePickerVisible(false);
        setEndTimePickerVisible(false);
        setIsTimePickerActive(false);

        // 重置提交状态
        setIsSubmitting(false);
    };

    // 切换时间刻度
    const changeTimeScale = (scale: string) => {
        setSelectedTimeScale(scale); // 更新选中的时间刻度状态
        const script = `
            if (window.handleReactNativeMessage) {
                window.handleReactNativeMessage({
                    type: 'changeTimeScale',
                    scale: '${scale}'
                });
            }
        `;
        webViewRef.current?.injectJavaScript(script);
    };

    // 搜索车间
    const searchDept = async (keyword: string) => {
        console.log('搜索车间，关键词:', keyword);
        console.log('请求参数:', { type: 2, device_name: keyword });

        if (!keyword.trim()) {
            setDeptList([]);
            return;
        }

        setIsLoading(true);
        try {
            const response = await getAllDept({
                type: 2,
                device_name: keyword
            });

            console.log('API响应:', response);

            if (response.code === 200) {
                setDeptList(response.data || []);
                console.log('车间列表:', response.data);
            } else {
                console.error('API错误:', response.message);
                Toast.fail(response.message || '获取车间信息失败', 2);
            }
        } catch (error) {
            console.error('搜索车间失败:', error);
            Toast.fail('网络请求失败', 2);
        } finally {
            setIsLoading(false);
        }
    };

    // 选择车间
    const selectDept = async (dept: any) => {
        setSelectedDept(dept);
        setIsDeptModalVisible(false);
        setIsTouchInterceptorActive(false);
        console.log('选择的车间:', dept);

        // 选择车间后调用API获取资源组调度信息
        try {
            const roomId = dept.id?.toString() || dept.dept_id?.toString() || '';
            console.log('准备调用API，车间ID:', roomId);

            const response = await getRoomResourceGroupScheduler({
                room_id: roomId
            });

            console.log('获取车间资源组调度信息响应:', response);

            if (response.code === 200) {
                // 处理成功响应，可以在这里更新甘特图数据
                console.log('车间资源组调度信息:', response.data);
                console.log('elements数量:', response.data.elements?.length || 0);
                console.log('tasks数量:', response.data.tasks?.length || 0);

                // 向WebView发送消息，更新甘特图数据
                const message = {
                    type: 'updateGanttData',
                    data: response.data
                };
                console.log('准备向WebView发送消息:', message);

                const script = `
                    if (window.handleReactNativeMessage) {
                        window.handleReactNativeMessage(${JSON.stringify(message)});
                    }
                `;
                webViewRef.current?.injectJavaScript(script);
                console.log('消息已发送到WebView');
            } else {
                console.error('获取车间资源组调度信息失败:', response.message);
                Toast.fail(response.message || '获取车间资源组调度信息失败', 2);
            }
        } catch (error) {
            console.error('调用车间资源组调度API失败:', error);
            Toast.fail('网络请求失败', 2);
        }
    };

    // 处理WebView消息
    const handleWebViewMessage = (event: any) => {
        try {
            const data = JSON.parse(event.nativeEvent.data);
            console.log('收到WebView消息:', data);

            // 处理日志消息
            if (data.type === 'log') {
                const level = data.level || 'log';
                const message = data.message || '';

                // 根据日志级别输出到控制台
                switch (level) {
                    case 'error':
                        console.error('[WebView]', message);
                        break;
                    case 'warn':
                        console.warn('[WebView]', message);
                        break;
                    case 'info':
                        console.info('[WebView]', message);
                        break;
                    default:
                        console.log('[WebView]', message);
                        break;
                }
            }

            // 处理任务点击消息
            if (data.type === 'taskClick') {
                console.log('收到任务点击消息:', data.task);
                setSelectedTask(data.task);
                setIsTaskDetailVisible(true);
            }

            // 处理资源点击消息
            if (data.type === 'resourceClick') {
                console.log('收到资源点击消息:', data.resource);
                setSelectedResource(data.resource);
                setIsResourceDetailVisible(true);
            }
        } catch (error) {
            console.error('解析WebView消息失败:', error);
        }
    };

    // 图标旋转动画
    const toggleDropdown = () => {
        const newVisible = !isDeptModalVisible;

        // 先更新状态，确保下拉框立即显示
        setIsDeptModalVisible(newVisible);

        // 然后执行动画
        const toValue = newVisible ? 1 : 0;
        Animated.timing(rotateAnim, {
            toValue,
            duration: 200,
            useNativeDriver: true,
        }).start();

        // 如果需要打开下拉框，则获取数据并延迟激活触摸拦截
        if (newVisible) {
            searchDept('1');
            // 延迟激活触摸拦截层，确保下拉框完全显示
            setTimeout(() => {
                setIsTouchInterceptorActive(true);
            }, 100);
        } else {
            // 关闭下拉框时立即禁用触摸拦截
            setIsTouchInterceptorActive(false);
        }
    };

    // 计算旋转角度
    const rotate = rotateAnim.interpolate({
        inputRange: [0, 1],
        outputRange: ['0deg', '180deg'],
    });

    // 工单下拉框旋转动画
    const workOrderDropdownRotate = useRef(new Animated.Value(0)).current;

    // 切换工单下拉框
    const toggleWorkOrderDropdown = () => {
        const newVisible = !isWorkOrderDropdownVisible;
        setIsWorkOrderDropdownVisible(newVisible);

        // 执行旋转动画
        const toValue = newVisible ? 1 : 0;
        Animated.timing(workOrderDropdownRotate, {
            toValue,
            duration: 200,
            useNativeDriver: true,
        }).start();
    };

    // 选择工单
    const selectWorkOrder = async (workOrder: any) => {
        setSelectedWorkOrder(workOrder);
        setIsWorkOrderDropdownVisible(false);
        setWorkOrderSearchText(''); // 清空搜索文本
        setSelectedBatch(null); // 清空选中的批次
        setProcessList([]); // 清空工序列表
        console.log('选中的工单:', workOrder);

        // 选择工单后自动获取批次列表
        if (workOrder.id) {
            await fetchBatchList(workOrder.id);
        }
    };

    // 获取批次列表
    const fetchBatchList = async (workOrderId: string) => {
        setIsBatchLoading(true);
        try {
            const response = await getAssignmentBatchOrderList({
                work_order_id: workOrderId
            });

            console.log('获取批次列表响应:', response);

            if (response.code === 200) {
                setBatchList(response.data || []);
                console.log('批次列表:', response.data);
            } else {
                console.error('获取批次列表失败:', response.msg);
                setBatchList([]);
            }
        } catch (error) {
            console.error('获取批次列表请求失败:', error);
            setBatchList([]);
        } finally {
            setIsBatchLoading(false);
        }
    };

    // 搜索工单
    const searchWorkOrders = async (keyword: string) => {
        if (!keyword.trim()) {
            setWorkOrderList([]);
            return;
        }

        setIsWorkOrderLoading(true);
        try {
            const response = await searchWorkOrder({
                keyword: keyword.trim(),
                current: 1,
                size: 15
            });

            console.log('工单搜索响应:', response);

            if (response.code === 200) {
                setWorkOrderList(response.data?.records || []);
                console.log('工单列表:', response.data?.records);
            } else {
                console.error('工单搜索失败:', response.msg);
                setWorkOrderList([]);
            }
        } catch (error) {
            console.error('工单搜索请求失败:', error);
            setWorkOrderList([]);
        } finally {
            setIsWorkOrderLoading(false);
        }
    };

    // 计算工单下拉框旋转角度
    const workOrderRotate = workOrderDropdownRotate.interpolate({
        inputRange: [0, 1],
        outputRange: ['0deg', '180deg'],
    });

    // 批次下拉框旋转动画
    const batchDropdownRotate = useRef(new Animated.Value(0)).current;

    // 派工下拉框旋转动画
    const deviceDropdownRotate = useRef(new Animated.Value(0)).current;
    const userDropdownRotate = useRef(new Animated.Value(0)).current;
    const stationDropdownRotate = useRef(new Animated.Value(0)).current;
    const lineDropdownRotate = useRef(new Animated.Value(0)).current;

    // 切换批次下拉框
    const toggleBatchDropdown = () => {
        const newVisible = !isBatchDropdownVisible;
        setIsBatchDropdownVisible(newVisible);

        // 执行旋转动画
        const toValue = newVisible ? 1 : 0;
        Animated.timing(batchDropdownRotate, {
            toValue,
            duration: 200,
            useNativeDriver: true,
        }).start();
    };

    // 切换设备下拉框
    const toggleDeviceDropdown = () => {
        const newVisible = !deviceDropdownVisible;
        setDeviceDropdownVisible(newVisible);

        // 执行旋转动画
        const toValue = newVisible ? 1 : 0;
        Animated.timing(deviceDropdownRotate, {
            toValue,
            duration: 200,
            useNativeDriver: true,
        }).start();
    };

    // 切换人员下拉框
    const toggleUserDropdown = () => {
        const newVisible = !userDropdownVisible;
        setUserDropdownVisible(newVisible);

        // 执行旋转动画
        const toValue = newVisible ? 1 : 0;
        Animated.timing(userDropdownRotate, {
            toValue,
            duration: 200,
            useNativeDriver: true,
        }).start();
    };

    // 切换工位下拉框
    const toggleStationDropdown = () => {
        const newVisible = !stationDropdownVisible;
        setStationDropdownVisible(newVisible);

        // 执行旋转动画
        const toValue = newVisible ? 1 : 0;
        Animated.timing(stationDropdownRotate, {
            toValue,
            duration: 200,
            useNativeDriver: true,
        }).start();
    };

    // 切换产线下拉框
    const toggleLineDropdown = () => {
        const newVisible = !lineDropdownVisible;
        setLineDropdownVisible(newVisible);

        // 执行旋转动画
        const toValue = newVisible ? 1 : 0;
        Animated.timing(lineDropdownRotate, {
            toValue,
            duration: 200,
            useNativeDriver: true,
        }).start();
    };

    // 选择批次
    const selectBatch = async (batch: any) => {
        setSelectedBatch(batch);
        setIsBatchDropdownVisible(false);
        console.log('选中的批次:', batch);

        // 选择批次后自动获取工序列表
        if (batch.batch_order_num) {
            await fetchProcessList(batch.batch_order_num);
        }
    };

    // 获取工序列表
    const fetchProcessList = async (batchOrderNum: string) => {
        setIsProcessLoading(true);
        try {
            const response = await getAssignmentMesTaskList({
                batch_order_num: batchOrderNum
            });

            console.log('获取工序列表响应:', response);

            if (response.code === 200) {
                setProcessList(response.data || []);
                console.log('工序列表:', response.data);
            } else {
                console.error('获取工序列表失败:', response.msg);
                setProcessList([]);
            }
        } catch (error) {
            console.error('获取工序列表请求失败:', error);
            setProcessList([]);
        } finally {
            setIsProcessLoading(false);
        }
    };

    // 工序点击处理
    const handleProcessClick = async (process: any) => {
        setSelectedProcess(process);
        console.log('选中的工序:', process);

        // 重置派工信息
        setWorkDeviceId(null);
        setWorkStationId(null);
        setWorkUserId(null);
        setWorkLineId(null);
        setWorkStartTime(null);
        setWorkEndTime(null);

        // 获取工序详情
        await fetchProcessDetail(process.id, selectedBatch?.batch_order_num);
    };

    // 获取工序详情
    const fetchProcessDetail = async (processId: string, batchOrderNum: string) => {
        if (!processId || !batchOrderNum) {
            console.error('缺少工序ID或批次号');
            return;
        }

        setIsProcessDetailLoading(true);
        try {
            const response = await getTaskInfo({
                id: processId,
                batch_order_num: batchOrderNum
            });

            console.log('获取工序详情响应:', response);

            if (response.code === 200) {
                setProcessDetail(response.data || {});
                console.log('工序详情:', response.data);
            } else {
                console.error('获取工序详情失败:', response.msg);
                setProcessDetail(null);
            }
        } catch (error) {
            console.error('获取工序详情请求失败:', error);
            setProcessDetail(null);
        } finally {
            setIsProcessDetailLoading(false);
        }
    };

    // 派工提交
    const handleDispatchSubmit = async () => {
        if (!selectedProcess || !selectedBatch || !workStartTime || !workEndTime) {
            Alert.alert('提示', '请选择工序、批次和时间');
            return;
        }

        // 根据capacity检查必填项
        const capacity = processDetail?.capacity;
        let isValid = true;
        let errorMessage = '';

        if (capacity === 2 && !workDeviceId) {
            isValid = false;
            errorMessage = '请选择设备';
        } else if (capacity === 4 && !workUserId) {
            isValid = false;
            errorMessage = '请选择人员';
        } else if ([1, 3].includes(capacity) && !workStationId) {
            isValid = false;
            errorMessage = '请选择工位';
        } else if (capacity === 5 && !workLineId) {
            isValid = false;
            errorMessage = '请选择产线';
        }

        if (!isValid) {
            Alert.alert('提示', errorMessage);
            return;
        }

        // 构建派工数据
        const dispatchData = {
            id: selectedProcess.id,
            batch_order_num: selectedBatch.batch_order_num,
            work_start: workStartTime,
            work_end: workEndTime,
            work_device_id: workDeviceId || undefined,
            work_station_id: workStationId || undefined,
            work_user_id: workUserId || undefined,
            work_line_id: workLineId || undefined,
            capacity: capacity
        };

        console.log('派工数据:', dispatchData);

        // 设置提交状态
        setIsSubmitting(true);

        try {
            // 调用派工提交API
            const response = await submitAssignmentTask(dispatchData);

            console.log('派工提交API响应:', response);

            if (response.code === 200) {
                // 提交成功
                Toast.success(response.msg || '派工信息已提交', 2);
                // 关闭派工卡片
                setIsResourceDetailVisible(false);
                // 重置状态
                resetDispatchState();

            } else {
                // 提交失败
                Toast.fail(response.message || response.msg || '派工提交失败，请重试', 2);
            }
        } catch (error) {
            console.error('派工提交失败:', error);
            Toast.fail('网络请求失败，请检查网络连接后重试', 2);
        } finally {
            // 重置提交状态
            setIsSubmitting(false);
        }
    };

    // 重置派工状态
    const resetDispatchState = () => {
        // 清空工单选择
        setSelectedWorkOrder(null);
        setWorkOrderSearchText('');
        setWorkOrderList([]);

        // 清空批次选择
        setSelectedBatch(null);
        setBatchList([]);

        // 清空工序选择
        setSelectedProcess(null);
        setProcessDetail(null);
        setProcessList([]);

        // 清空派工信息
        setWorkDeviceId(null);
        setWorkStationId(null);
        setWorkUserId(null);
        setWorkLineId(null);
        setWorkStartTime(null);
        setWorkEndTime(null);

        // 清空下拉框状态
        setDeviceDropdownVisible(false);
        setUserDropdownVisible(false);
        setStationDropdownVisible(false);
        setLineDropdownVisible(false);

        // 重置旋转动画状态
        deviceDropdownRotate.setValue(0);
        userDropdownRotate.setValue(0);
        stationDropdownRotate.setValue(0);
        lineDropdownRotate.setValue(0);

        // 清空搜索文本
        setDeptSearchText('');
        setDeptList([]);

        // 重置加载状态
        setIsWorkOrderLoading(false);
        setIsBatchLoading(false);
        setIsProcessLoading(false);
        setIsProcessDetailLoading(false);

        // 重置时间选择器状态
        setStartTimePickerVisible(false);
        setEndTimePickerVisible(false);
        setIsTimePickerActive(false);

        // 重置提交状态
        setIsSubmitting(false);
    };

    // 计算批次下拉框旋转角度
    const batchRotate = batchDropdownRotate.interpolate({
        inputRange: [0, 1],
        outputRange: ['0deg', '180deg'],
    });

    // 计算派工下拉框旋转角度
    const deviceRotate = deviceDropdownRotate.interpolate({
        inputRange: [0, 1],
        outputRange: ['0deg', '180deg'],
    });

    const userRotate = userDropdownRotate.interpolate({
        inputRange: [0, 1],
        outputRange: ['0deg', '180deg'],
    });

    const stationRotate = stationDropdownRotate.interpolate({
        inputRange: [0, 1],
        outputRange: ['0deg', '180deg'],
    });

    const lineRotate = lineDropdownRotate.interpolate({
        inputRange: [0, 1],
        outputRange: ['0deg', '180deg'],
    });

    // 获取对比色
    const getContrastColor = (hexColor: string) => {
        if (hexColor.startsWith('#')) {
            hexColor = hexColor.substring(1);
        }
        const r = parseInt(hexColor.substring(0, 2), 16);
        const g = parseInt(hexColor.substring(2, 4), 16);
        const b = parseInt(hexColor.substring(4, 6), 16);

        // 计算亮度 (Y)
        const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;

        // 如果亮度大于0.5，则使用深色文字，否则使用浅色文字
        return luminance > 0.5 ? '#000000' : '#FFFFFF';
    };

    // 格式化时间显示
    const formatTimeDisplay = (timeStr: string | null) => {
        if (!timeStr) return '';
        // 如果时间包含秒，则显示到秒；否则显示到分钟
        if (timeStr.includes(':00')) {
            return timeStr.slice(0, 16); // 显示到分钟
        }
        return timeStr; // 显示完整时间
    };

    // 获取设备名称
    const getDeviceName = (id: string) => {
        const device = processDetail?.device_list?.find((d: any) => d.id === id);
        return device ? device.device_num : 'N/A';
    };

    // 获取人员名称
    const getUserName = (id: string) => {
        const user = processDetail?.user_list?.find((u: any) => u.id === id);
        return user ? user.user_name : 'N/A';
    };

    // 获取工位名称
    const getStationName = (id: string) => {
        const station = processDetail?.station_list?.find((s: any) => s.id === id);
        return station ? station.station_num : 'N/A';
    };

    // 获取产线名称
    const getLineName = (id: string) => {
        const line = processDetail?.line_list?.find((l: any) => l.id === id);
        return line ? line.line_num : 'N/A';
    };

    // 监听时间选择器状态变化
    useEffect(() => {
        console.log('时间选择器状态变化:', {
            startTimePickerVisible,
            endTimePickerVisible,
            isTimePickerActive
        });

        // 当时间选择器关闭后，强制触发布局重新计算
        if (!startTimePickerVisible && !endTimePickerVisible && !isTimePickerActive) {
            // 使用setTimeout确保状态更新完成后再触发重新渲染
            setTimeout(() => {
                // 强制重新渲染
                setForceUpdate(prev => prev + 1);
            }, 100);
        }
    }, [startTimePickerVisible, endTimePickerVisible, isTimePickerActive]);

    return (
        <SafeAreaView style={styles.container}>
            {/* 头部区域 - 与ProductionReport保持一致 */}
            <View style={styles.header}>
                <Image
                    source={require('../../../../assets/terminal/home-header.png')}
                    style={styles.headerBackground}
                    resizeMode="cover"
                />
                <View style={styles.headerContent}>
                    {/* <Image
                        source={require('../../../../assets/terminal/home-logo.png')}
                        style={styles.logo}
                        resizeMode="contain"
                    /> */}
                    <Text style={styles.headerText}>
                        MES终端服务系统
                    </Text>
                </View>
                <TouchableOpacity
                    onPress={onBackPress}
                    style={styles.backButton}
                >
                    <Image
                        source={require('../../../../assets/fanhui.png')}
                        style={styles.backIcon}
                    />
                </TouchableOpacity>
            </View>

            {/* 控制面板 */}
            <View style={styles.controlPanel}>
                <View style={styles.leftControls}>
                    <TouchableOpacity style={styles.controlButton} onPress={clearGanttData}>
                        <Text style={styles.controlButtonText}>清除所有</Text>
                    </TouchableOpacity>
                    <TouchableOpacity
                        style={[
                            styles.controlButton,
                            selectedTimeScale === 'hour' && styles.activeButton
                        ]}
                        onPress={() => changeTimeScale('hour')}
                    >
                        <Text style={[
                            styles.controlButtonText,
                            selectedTimeScale === 'hour' && styles.activeButtonText
                        ]}>小时</Text>
                    </TouchableOpacity>
                    <TouchableOpacity
                        style={[
                            styles.controlButton,
                            selectedTimeScale === 'day' && styles.activeButton
                        ]}
                        onPress={() => changeTimeScale('day')}
                    >
                        <Text style={[
                            styles.controlButtonText,
                            selectedTimeScale === 'day' && styles.activeButtonText
                        ]}>天</Text>
                    </TouchableOpacity>
                    <TouchableOpacity
                        style={[
                            styles.controlButton,
                            selectedTimeScale === 'week' && styles.activeButton
                        ]}
                        onPress={() => changeTimeScale('week')}
                    >
                        <Text style={[
                            styles.controlButtonText,
                            selectedTimeScale === 'week' && styles.activeButtonText
                        ]}>周</Text>
                    </TouchableOpacity>
                    <TouchableOpacity
                        style={[
                            styles.controlButton,
                            selectedTimeScale === 'month' && styles.activeButton
                        ]}
                        onPress={() => changeTimeScale('month')}
                    >
                        <Text style={[
                            styles.controlButtonText,
                            selectedTimeScale === 'month' && styles.activeButtonText
                        ]}>月</Text>
                    </TouchableOpacity>
                    <TouchableOpacity
                        style={[
                            styles.controlButton,
                            selectedTimeScale === 'quarter' && styles.activeButton
                        ]}
                        onPress={() => changeTimeScale('quarter')}
                    >
                        <Text style={[
                            styles.controlButtonText,
                            selectedTimeScale === 'quarter' && styles.activeButtonText
                        ]}>季度</Text>
                    </TouchableOpacity>
                    <TouchableOpacity
                        style={[
                            styles.controlButton,
                            selectedTimeScale === 'year' && styles.activeButton
                        ]}
                        onPress={() => changeTimeScale('year')}
                    >
                        <Text style={[
                            styles.controlButtonText,
                            selectedTimeScale === 'year' && styles.activeButtonText
                        ]}>年</Text>
                    </TouchableOpacity>
                </View>
                <View style={styles.rightControls}>
                    <View style={styles.dropdownWrapper}>
                        <TouchableOpacity
                            style={styles.dropdownContainer}
                            onPress={(e) => {
                                e.stopPropagation();
                                toggleDropdown();
                            }}
                        >
                            <Text style={styles.dropdownText}>{selectedDept ? selectedDept.dept_name : '车间'}</Text>
                            <Animated.Image
                                source={require('../../../../assets/xiala.png')}
                                style={[styles.dropdownIcon, { transform: [{ rotate }] }]}
                            />
                        </TouchableOpacity>

                        {/* 直接显示的下拉列表 */}
                        {isDeptModalVisible && (
                            <View
                                style={[styles.dropdownList, { zIndex: 1001 }]}
                                onTouchStart={(e) => e.stopPropagation()}
                                onTouchEnd={(e) => e.stopPropagation()}
                            >
                                {isLoading ? (
                                    <Text style={styles.loadingText}>加载中...</Text>
                                ) : (
                                    <View style={styles.deptList}>
                                        {deptList && deptList.length > 0 ? (
                                            deptList.map((item: any) => (
                                                <TouchableOpacity
                                                    key={item.id?.toString() || Math.random().toString()}
                                                    style={styles.deptItem}
                                                    onPress={(e) => {
                                                        e.stopPropagation();
                                                        selectDept(item);
                                                    }}
                                                    activeOpacity={0.7}
                                                >
                                                    <Text style={styles.deptItemText}>{item.dept_name}</Text>
                                                </TouchableOpacity>
                                            ))
                                        ) : (
                                            <Text style={styles.emptyText}>
                                                暂无车间数据
                                            </Text>
                                        )}
                                    </View>
                                )}
                            </View>
                        )}
                    </View>
                </View>
            </View>

            {/* 甘特图区域 */}
            <View style={styles.ganttContainer}>
                {/* 触摸拦截层 - 当下拉框显示时阻止甘特图触摸事件 */}
                {isTouchInterceptorActive && (
                    <View
                        style={{
                            position: 'absolute',
                            top: 0,
                            left: 0,
                            right: 0,
                            bottom: 0,
                            zIndex: 1000,
                            backgroundColor: 'transparent'
                        }}
                        onTouchStart={(e) => {
                            e.stopPropagation();
                            e.preventDefault();
                        }}
                        onTouchEnd={(e) => {
                            e.stopPropagation();
                            e.preventDefault();
                        }}
                    />
                )}

                {/* 工单详情弹窗 - 只有点击任务才显示 */}
                <Modal
                    visible={isTaskDetailVisible}
                    transparent={true}
                    animationType="fade"
                    onRequestClose={() => setIsTaskDetailVisible(false)}
                >
                    <TouchableWithoutFeedback onPress={() => setIsTaskDetailVisible(false)}>
                        <View style={styles.modalOverlay}>
                            <TouchableWithoutFeedback onPress={(e) => e.stopPropagation()}>
                                <View style={styles.taskDetailModal}>
                                    <View style={styles.taskDetailHeader}>
                                        <Text style={styles.taskDetailTitle}>工单详情</Text>
                                        <TouchableOpacity
                                            onPress={() => setIsTaskDetailVisible(false)}
                                            style={styles.closeButton}
                                        >
                                            <Text style={styles.closeButtonText}>×</Text>
                                        </TouchableOpacity>
                                    </View>

                                    {selectedTask && (
                                        <View style={styles.taskDetailContent}>
                                            <View style={styles.taskDetailRow}>
                                                <Text style={styles.taskDetailLabel}>工单号：</Text>
                                                <Text style={styles.taskDetailValue}>{selectedTask.work_order_num || 'N/A'}</Text>
                                            </View>
                                            <View style={styles.taskDetailRow}>
                                                <Text style={styles.taskDetailLabel}>批次：</Text>
                                                <Text style={styles.taskDetailValue}>{selectedTask.batch_order_num || 'N/A'}</Text>
                                            </View>
                                            <View style={styles.taskDetailRow}>
                                                <Text style={styles.taskDetailLabel}>产品名称：</Text>
                                                <Text style={styles.taskDetailValue}>{selectedTask.product_name || 'N/A'}</Text>
                                            </View>
                                            <View style={styles.taskDetailRow}>
                                                <Text style={styles.taskDetailLabel}>工序号：</Text>
                                                <Text style={styles.taskDetailValue}>{selectedTask.mbom_num || 'N/A'}</Text>
                                            </View>
                                            <View style={styles.taskDetailRow}>
                                                <Text style={styles.taskDetailLabel}>工艺号：</Text>
                                                <Text style={styles.taskDetailValue}>{selectedTask.process_num || 'N/A'}</Text>
                                            </View>
                                            <View style={styles.taskDetailRow}>
                                                <Text style={styles.taskDetailLabel}>派工设备：</Text>
                                                <Text style={styles.taskDetailValue}>{selectedTask.work_device_num || 'N/A'}</Text>
                                            </View>
                                            <View style={styles.taskDetailRow}>
                                                <Text style={styles.taskDetailLabel}>开始时间：</Text>
                                                <Text style={styles.taskDetailValue}>{selectedTask.work_start || 'N/A'}</Text>
                                            </View>
                                            <View style={styles.taskDetailRow}>
                                                <Text style={styles.taskDetailLabel}>结束时间：</Text>
                                                <Text style={styles.taskDetailValue}>{selectedTask.work_end || 'N/A'}</Text>
                                            </View>
                                        </View>
                                    )}
                                </View>
                            </TouchableWithoutFeedback>
                        </View>
                    </TouchableWithoutFeedback>
                </Modal>

                {/* 派工卡片 - 点击左侧任务列显示 */}
                <Modal
                    visible={isResourceDetailVisible && !isTimePickerActive}
                    transparent={true}
                    animationType="slide"
                    onRequestClose={() => {
                        clearDispatchInfo();
                        setIsResourceDetailVisible(false);
                    }}
                    statusBarTranslucent={false}
                >
                    <View style={styles.resourceModalOverlay}>
                        <View
                            style={styles.resourceDetailCard}
                            onLayout={(event) => {
                                // 确保卡片有正确的高度
                                const { height } = event.nativeEvent.layout;
                                if (height > 0) {
                                    // 卡片已经渲染完成
                                }
                            }}
                        >
                            {/* 头部标题区域 - 固定 */}
                            <View style={styles.resourceDetailHeader}>
                                <Text style={styles.resourceDetailTitle}>派工</Text>
                                <TouchableOpacity
                                    onPress={() => {
                                        clearDispatchInfo();
                                        setIsResourceDetailVisible(false);
                                    }}
                                    style={styles.closeButton}
                                >
                                    <Text style={styles.closeButtonText}>×</Text>
                                </TouchableOpacity>
                            </View>

                            {/* 内容区域 - 可滚动 */}
                            <ScrollView
                                key={`content-${forceUpdate}`}
                                style={styles.resourceDetailContent}
                                showsVerticalScrollIndicator={true}
                                contentContainerStyle={styles.resourceDetailContentContainer}
                                nestedScrollEnabled={true}
                                scrollEnabled={true}
                                bounces={true}
                                alwaysBounceVertical={true}
                                keyboardShouldPersistTaps="handled"
                                onLayout={(event) => {
                                    // 确保ScrollView有正确的高度
                                    const { height } = event.nativeEvent.layout;
                                    if (height > 0) {
                                        // ScrollView已经渲染，可以滚动
                                    }
                                }}
                            >
                                {/* 工单选择区域 */}
                                <View style={styles.workOrderSection}>
                                    <Text style={styles.sectionLabel}>选择工单</Text>
                                    <View style={styles.workOrderDropdownContainer}>
                                        <TouchableOpacity
                                            style={styles.workOrderDropdown}
                                            onPress={toggleWorkOrderDropdown}
                                        >
                                            <Text style={[
                                                styles.workOrderDropdownText,
                                                !selectedWorkOrder && styles.placeholderText
                                            ]}>
                                                {selectedWorkOrder ? selectedWorkOrder.work_order_num : '请选择工单'}
                                            </Text>
                                            <Animated.Image
                                                source={require('../../../../assets/xiala.png')}
                                                style={[
                                                    styles.workOrderDropdownIcon,
                                                    { transform: [{ rotate: workOrderRotate }] }
                                                ]}
                                            />
                                        </TouchableOpacity>

                                        {/* 工单下拉列表 */}
                                        {isWorkOrderDropdownVisible && (
                                            <View style={styles.workOrderDropdownList}>
                                                {/* 搜索输入框 */}
                                                <View style={styles.workOrderSearchContainer}>
                                                    <TextInput
                                                        style={styles.workOrderSearchInput}
                                                        placeholder="输入工单号搜索..."
                                                        value={workOrderSearchText}
                                                        onChangeText={(text) => {
                                                            setWorkOrderSearchText(text);
                                                            // 延迟搜索，避免频繁请求
                                                            if (text.trim()) {
                                                                setTimeout(() => {
                                                                    searchWorkOrders(text);
                                                                }, 500);
                                                            } else {
                                                                setWorkOrderList([]);
                                                            }
                                                        }}
                                                        placeholderTextColor="#999"
                                                    />
                                                </View>

                                                {/* 工单列表 */}
                                                {isWorkOrderLoading ? (
                                                    <View style={styles.workOrderLoadingContainer}>
                                                        <Text style={styles.workOrderLoadingText}>搜索中...</Text>
                                                    </View>
                                                ) : (
                                                    <ScrollView
                                                        style={styles.workOrderList}
                                                        showsVerticalScrollIndicator={false}
                                                        nestedScrollEnabled={true}
                                                    >
                                                        {workOrderList && workOrderList.length > 0 ? (
                                                            workOrderList.map((item: any) => (
                                                                <TouchableOpacity
                                                                    key={item.id?.toString() || Math.random().toString()}
                                                                    style={styles.workOrderItem}
                                                                    onPress={() => selectWorkOrder(item)}
                                                                    activeOpacity={0.7}
                                                                >
                                                                    <Text style={styles.workOrderItemText}>
                                                                        {item.work_order_num}
                                                                    </Text>
                                                                    <Text style={styles.workOrderItemSubText}>
                                                                        {item.product_name || 'N/A'}
                                                                    </Text>
                                                                </TouchableOpacity>
                                                            ))
                                                        ) : (
                                                            <Text style={styles.workOrderEmptyText}>
                                                                {workOrderSearchText ? '未找到匹配的工单' : '暂无工单数据'}
                                                            </Text>
                                                        )}
                                                    </ScrollView>
                                                )}
                                            </View>
                                        )}
                                    </View>
                                </View>

                                {/* 批次选择区域 */}
                                <View style={styles.batchSection}>
                                    <Text style={styles.sectionLabel}>选择批次</Text>
                                    <View style={styles.batchDropdownContainer}>
                                        <TouchableOpacity
                                            style={styles.batchDropdown}
                                            onPress={toggleBatchDropdown}
                                        >
                                            <Text style={[
                                                styles.batchDropdownText,
                                                !selectedBatch && styles.placeholderText
                                            ]}>
                                                {selectedBatch ? selectedBatch.batch_order_num : '请选择批次'}
                                            </Text>
                                            <Animated.Image
                                                source={require('../../../../assets/xiala.png')}
                                                style={[
                                                    styles.batchDropdownIcon,
                                                    { transform: [{ rotate: batchRotate }] }
                                                ]}
                                            />
                                        </TouchableOpacity>

                                        {/* 批次下拉列表 */}
                                        {isBatchDropdownVisible && (
                                            <View style={styles.batchDropdownList}>
                                                {isBatchLoading ? (
                                                    <View style={styles.batchLoadingContainer}>
                                                        <Text style={styles.batchLoadingText}>加载中...</Text>
                                                    </View>
                                                ) : (
                                                    <ScrollView
                                                        style={styles.batchList}
                                                        showsVerticalScrollIndicator={false}
                                                        nestedScrollEnabled={true}
                                                    >
                                                        {batchList && batchList.length > 0 ? (
                                                            batchList.map((item: any) => (
                                                                <TouchableOpacity
                                                                    key={item.id?.toString() || Math.random().toString()}
                                                                    style={styles.batchItem}
                                                                    onPress={() => selectBatch(item)}
                                                                    activeOpacity={0.7}
                                                                >
                                                                    <Text style={styles.batchItemText}>
                                                                        {item.batch_order_num}
                                                                    </Text>
                                                                </TouchableOpacity>
                                                            ))
                                                        ) : (
                                                            <Text style={styles.batchEmptyText}>
                                                                暂无批次数据
                                                            </Text>
                                                        )}
                                                    </ScrollView>
                                                )}
                                            </View>
                                        )}
                                    </View>
                                </View>

                                {/* 工序展示区域 */}
                                <View style={styles.processSection}>
                                    <Text style={styles.sectionLabel}>工序</Text>
                                    {isProcessLoading ? (
                                        <View style={styles.processLoadingContainer}>
                                            <Text style={styles.processLoadingText}>加载中...</Text>
                                        </View>
                                    ) : processList.length > 0 ? (
                                        <ScrollView
                                            horizontal
                                            showsHorizontalScrollIndicator={false}
                                            style={styles.processScrollView}
                                        >
                                            {processList.map((process, index) => {
                                                // 计算文字颜色（与背景色形成对比）
                                                const backgroundColor = process.bom_color || '#f8f9fa';
                                                const textColor = getContrastColor(backgroundColor);
                                                const isSelected = selectedProcess?.id === process.id;

                                                return (
                                                    <TouchableOpacity
                                                        key={process.id}
                                                        style={[
                                                            styles.processCard,
                                                            { backgroundColor: backgroundColor },
                                                            isSelected && styles.selectedProcessCard
                                                        ]}
                                                        onPress={() => handleProcessClick(process)}
                                                    >
                                                        <Text style={[styles.processNumber, { color: textColor }]}>
                                                            {process.mbom_num}
                                                        </Text>
                                                        <Text style={[styles.processName, { color: textColor }]}>
                                                            {process.process_name}
                                                        </Text>
                                                        {isSelected && (
                                                            <View style={styles.processCheckmark}>
                                                                <Text style={styles.processCheckmarkText}>✓</Text>
                                                            </View>
                                                        )}
                                                    </TouchableOpacity>
                                                );
                                            })}
                                        </ScrollView>
                                    ) : (
                                        <Text style={styles.processEmptyText}>暂无工序数据</Text>
                                    )}
                                </View>

                                {/* 派工信息区域 - 根据capacity显示 */}
                                {selectedProcess && processDetail && (
                                    <View style={styles.dispatchInfoSection}>
                                        {/* 设备选择 - capacity = 2 */}
                                        {processDetail.capacity === 2 && (
                                            <View style={styles.dispatchItem}>
                                                <Text style={styles.dispatchLabel}>设备</Text>
                                                <View style={styles.dispatchDropdownContainer}>
                                                    <TouchableOpacity
                                                        style={styles.dispatchDropdown}
                                                        onPress={toggleDeviceDropdown}
                                                    >
                                                        <Text style={[
                                                            styles.dispatchDropdownText,
                                                            !workDeviceId && styles.placeholderText
                                                        ]}>
                                                            {workDeviceId ? getDeviceName(workDeviceId) : '请选择设备'}
                                                        </Text>
                                                        <Animated.Image
                                                            source={require('../../../../assets/xiala.png')}
                                                            style={[
                                                                styles.dispatchDropdownIcon,
                                                                { transform: [{ rotate: deviceRotate }] }
                                                            ]}
                                                        />
                                                    </TouchableOpacity>

                                                    {/* 设备下拉列表 */}
                                                    {deviceDropdownVisible && (
                                                        <View style={styles.dispatchDropdownList}>
                                                            <ScrollView
                                                                style={styles.dispatchDropdownScrollView}
                                                                showsVerticalScrollIndicator={false}
                                                                nestedScrollEnabled={true}
                                                            >
                                                                {processDetail.device_list && processDetail.device_list.length > 0 ? (
                                                                    processDetail.device_list.map((item: any) => (
                                                                        <TouchableOpacity
                                                                            key={item.id?.toString() || Math.random().toString()}
                                                                            style={styles.dispatchDropdownItem}
                                                                            onPress={() => {
                                                                                setWorkDeviceId(item.id);
                                                                                setDeviceDropdownVisible(false);
                                                                                // 重置旋转动画
                                                                                deviceDropdownRotate.setValue(0);
                                                                            }}
                                                                            activeOpacity={0.7}
                                                                        >
                                                                            <Text style={styles.dispatchDropdownItemText}>
                                                                                {item.device_num}
                                                                            </Text>
                                                                        </TouchableOpacity>
                                                                    ))
                                                                ) : (
                                                                    <Text style={styles.dispatchDropdownEmptyText}>
                                                                        暂无设备数据
                                                                    </Text>
                                                                )}
                                                            </ScrollView>
                                                        </View>
                                                    )}
                                                </View>
                                            </View>
                                        )}

                                        {/* 人员选择 - capacity = 4 */}
                                        {processDetail.capacity === 4 && (
                                            <View style={styles.dispatchItem}>
                                                <Text style={styles.dispatchLabel}>人员</Text>
                                                <View style={styles.dispatchDropdownContainer}>
                                                    <TouchableOpacity
                                                        style={styles.dispatchDropdown}
                                                        onPress={toggleUserDropdown}
                                                    >
                                                        <Text style={[
                                                            styles.dispatchDropdownText,
                                                            !workUserId && styles.placeholderText
                                                        ]}>
                                                            {workUserId ? getUserName(workUserId) : '请选择人员'}
                                                        </Text>
                                                        <Animated.Image
                                                            source={require('../../../../assets/xiala.png')}
                                                            style={[
                                                                styles.dispatchDropdownIcon,
                                                                { transform: [{ rotate: userRotate }] }
                                                            ]}
                                                        />
                                                    </TouchableOpacity>

                                                    {/* 人员下拉列表 */}
                                                    {userDropdownVisible && (
                                                        <View style={styles.dispatchDropdownList}>
                                                            <ScrollView
                                                                style={styles.dispatchDropdownScrollView}
                                                                showsVerticalScrollIndicator={false}
                                                                nestedScrollEnabled={true}
                                                            >
                                                                {processDetail.user_list && processDetail.user_list.length > 0 ? (
                                                                    processDetail.user_list.map((item: any) => (
                                                                        <TouchableOpacity
                                                                            key={item.id?.toString() || Math.random().toString()}
                                                                            style={styles.dispatchDropdownItem}
                                                                            onPress={() => {
                                                                                setWorkUserId(item.id);
                                                                                setUserDropdownVisible(false);
                                                                                // 重置旋转动画
                                                                                userDropdownRotate.setValue(0);
                                                                            }}
                                                                            activeOpacity={0.7}
                                                                        >
                                                                            <Text style={styles.dispatchDropdownItemText}>
                                                                                {item.user_name}
                                                                            </Text>
                                                                        </TouchableOpacity>
                                                                    ))
                                                                ) : (
                                                                    <Text style={styles.dispatchDropdownEmptyText}>
                                                                        暂无人员数据
                                                                    </Text>
                                                                )}
                                                            </ScrollView>
                                                        </View>
                                                    )}
                                                </View>
                                            </View>
                                        )}

                                        {/* 工位选择 - capacity = 1 或 3 */}
                                        {[1, 3].includes(processDetail.capacity) && (
                                            <View style={styles.dispatchItem}>
                                                <Text style={styles.dispatchLabel}>工位</Text>
                                                <View style={styles.dispatchDropdownContainer}>
                                                    <TouchableOpacity
                                                        style={styles.dispatchDropdown}
                                                        onPress={toggleStationDropdown}
                                                    >
                                                        <Text style={[
                                                            styles.dispatchDropdownText,
                                                            !workStationId && styles.placeholderText
                                                        ]}>
                                                            {workStationId ? getStationName(workStationId) : '请选择工位'}
                                                        </Text>
                                                        <Animated.Image
                                                            source={require('../../../../assets/xiala.png')}
                                                            style={[
                                                                styles.dispatchDropdownIcon,
                                                                { transform: [{ rotate: stationRotate }] }
                                                            ]}
                                                        />
                                                    </TouchableOpacity>

                                                    {/* 工位下拉列表 */}
                                                    {stationDropdownVisible && (
                                                        <View style={styles.dispatchDropdownList}>
                                                            <ScrollView
                                                                style={styles.dispatchDropdownScrollView}
                                                                showsVerticalScrollIndicator={false}
                                                                nestedScrollEnabled={true}
                                                            >
                                                                {processDetail.station_list && processDetail.station_list.length > 0 ? (
                                                                    processDetail.station_list.map((item: any) => (
                                                                        <TouchableOpacity
                                                                            key={item.id?.toString() || Math.random().toString()}
                                                                            style={styles.dispatchDropdownItem}
                                                                            onPress={() => {
                                                                                setWorkStationId(item.id);
                                                                                setStationDropdownVisible(false);
                                                                                // 重置旋转动画
                                                                                stationDropdownRotate.setValue(0);
                                                                            }}
                                                                            activeOpacity={0.7}
                                                                        >
                                                                            <Text style={styles.dispatchDropdownItemText}>
                                                                                {item.station_num}
                                                                            </Text>
                                                                        </TouchableOpacity>
                                                                    ))
                                                                ) : (
                                                                    <Text style={styles.dispatchDropdownEmptyText}>
                                                                        暂无工位数据
                                                                    </Text>
                                                                )}
                                                            </ScrollView>
                                                        </View>
                                                    )}
                                                </View>
                                            </View>
                                        )}

                                        {/* 产线选择 - capacity = 5 */}
                                        {processDetail.capacity === 5 && (
                                            <View style={styles.dispatchItem}>
                                                <Text style={styles.dispatchLabel}>产线</Text>
                                                <View style={styles.dispatchDropdownContainer}>
                                                    <TouchableOpacity
                                                        style={styles.dispatchDropdown}
                                                        onPress={toggleLineDropdown}
                                                    >
                                                        <Text style={[
                                                            styles.dispatchDropdownText,
                                                            !workLineId && styles.placeholderText
                                                        ]}>
                                                            {workLineId ? getLineName(workLineId) : '请选择产线'}
                                                        </Text>
                                                        <Animated.Image
                                                            source={require('../../../../assets/xiala.png')}
                                                            style={[
                                                                styles.dispatchDropdownIcon,
                                                                { transform: [{ rotate: lineRotate }] }
                                                            ]}
                                                        />
                                                    </TouchableOpacity>

                                                    {/* 产线下拉列表 */}
                                                    {lineDropdownVisible && (
                                                        <View style={styles.dispatchDropdownList}>
                                                            <ScrollView
                                                                style={styles.dispatchDropdownScrollView}
                                                                showsVerticalScrollIndicator={false}
                                                                nestedScrollEnabled={true}
                                                            >
                                                                {processDetail.line_list && processDetail.line_list.length > 0 ? (
                                                                    processDetail.line_list.map((item: any) => (
                                                                        <TouchableOpacity
                                                                            key={item.id?.toString() || Math.random().toString()}
                                                                            style={styles.dispatchDropdownItem}
                                                                            onPress={() => {
                                                                                setWorkLineId(item.id);
                                                                                setLineDropdownVisible(false);
                                                                                // 重置旋转动画
                                                                                lineDropdownRotate.setValue(0);
                                                                            }}
                                                                            activeOpacity={0.7}
                                                                        >
                                                                            <Text style={styles.dispatchDropdownItemText}>
                                                                                {item.line_num}
                                                                            </Text>
                                                                        </TouchableOpacity>
                                                                    ))
                                                                ) : (
                                                                    <Text style={styles.dispatchDropdownEmptyText}>
                                                                        暂无产线数据
                                                                    </Text>
                                                                )}
                                                            </ScrollView>
                                                        </View>
                                                    )}
                                                </View>
                                            </View>
                                        )}


                                    </View>
                                )}
                                {/* 时间选择 */}
                                <View style={styles.dispatchItem}>
                                    <Text style={styles.dispatchLabel}>时间</Text>
                                    <View style={styles.timeSelectionContainer}>
                                        <View style={styles.timeInput}>
                                            <TouchableOpacity
                                                style={styles.timeSelector}
                                                activeOpacity={0.7}
                                                onPress={() => {
                                                    console.log('点击开始时间选择器');
                                                    setIsTimePickerActive(true);
                                                    setStartTimePickerVisible(true);
                                                    console.log('设置状态: startTimePickerVisible = true, isTimePickerActive = true');
                                                }}
                                            >
                                                <Text style={styles.timeText}>
                                                    {workStartTime ? formatTimeDisplay(workStartTime) : '请选择开始时间'}
                                                </Text>

                                            </TouchableOpacity>
                                        </View>
                                        <Text style={styles.timeSeparator}>至</Text>
                                        <View style={styles.timeInput}>
                                            <TouchableOpacity
                                                style={styles.timeSelector}
                                                activeOpacity={0.7}
                                                onPress={() => {
                                                    console.log('点击结束时间选择器');
                                                    setIsTimePickerActive(true);
                                                    setEndTimePickerVisible(true);
                                                    console.log('设置状态: endTimePickerVisible = true, isTimePickerActive = true');
                                                }}
                                            >
                                                <Text style={styles.timeText}>
                                                    {workEndTime ? formatTimeDisplay(workEndTime) : '请选择结束时间'}
                                                </Text>

                                            </TouchableOpacity>
                                        </View>
                                    </View>
                                </View>
                            </ScrollView>

                            {/* 底部按钮区域 - 始终显示，固定在底部 */}
                            <View key={`footer-${forceUpdate}`} style={styles.resourceDetailFooter}>
                                <TouchableOpacity
                                    style={[
                                        styles.submitButton,
                                        isSubmitting && styles.submitButtonDisabled
                                    ]}
                                    onPress={handleDispatchSubmit}
                                    disabled={isSubmitting}
                                >
                                    <Text style={[
                                        styles.submitButtonText,
                                        isSubmitting && styles.submitButtonTextDisabled
                                    ]}>
                                        {isSubmitting ? '提交中...' : '确认'}
                                    </Text>
                                </TouchableOpacity>
                                <TouchableOpacity
                                    style={styles.cancelButton}
                                    onPress={() => {
                                        clearDispatchInfo();
                                        setIsResourceDetailVisible(false);
                                    }}
                                    disabled={isSubmitting}
                                >
                                    <Text style={styles.cancelButtonText}>取消</Text>
                                </TouchableOpacity>
                            </View>
                        </View>
                    </View>
                </Modal>

                {/* DatePicker弹出层 - 移到Modal外部，设置更高的z-index */}
                <View style={styles.datePickerOverlay}>
                    {/* 开始时间选择器 */}
                    {startTimePickerVisible && (
                        <View style={styles.datePickerContainer}>
                            <DatePicker
                                visible={startTimePickerVisible}
                                value={workStartTime ? new Date(workStartTime) : new Date()}
                                precision="second"
                                minDate={new Date(2000, 0, 1)}
                                maxDate={new Date(2100, 11, 31, 23, 59, 59)}
                                onChange={date => {
                                    console.log('开始时间选择器 onChange:', date);
                                    if (date) {
                                        const y = date.getFullYear();
                                        const m = String(date.getMonth() + 1).padStart(2, '0');
                                        const d = String(date.getDate()).padStart(2, '0');
                                        const h = String(date.getHours()).padStart(2, '0');
                                        const min = String(date.getMinutes()).padStart(2, '0');
                                        const s = String(date.getSeconds()).padStart(2, '0');
                                        setWorkStartTime(`${y}-${m}-${d} ${h}:${min}:${s}`);
                                    } else {
                                        setWorkStartTime('');
                                    }
                                    setStartTimePickerVisible(false);
                                    setIsTimePickerActive(false);
                                }}
                                format="YYYY-MM-DD HH:mm:ss"
                                onVisibleChange={(visible) => {
                                    console.log('开始时间选择器 onVisibleChange:', visible);
                                    if (!visible) {
                                        setStartTimePickerVisible(false);
                                        setIsTimePickerActive(false);
                                    }
                                }}
                            />
                        </View>
                    )}

                    {/* 结束时间选择器 */}
                    {endTimePickerVisible && (
                        <View style={styles.datePickerContainer}>
                            <DatePicker
                                visible={endTimePickerVisible}
                                value={workEndTime ? new Date(workEndTime) : new Date()}
                                precision="second"
                                minDate={new Date(2000, 0, 1)}
                                maxDate={new Date(2100, 11, 31, 23, 59, 59)}
                                onChange={date => {
                                    console.log('结束时间选择器 onChange:', date);
                                    if (date) {
                                        const y = date.getFullYear();
                                        const m = String(date.getMonth() + 1).padStart(2, '0');
                                        const d = String(date.getDate()).padStart(2, '0');
                                        const h = String(date.getHours()).padStart(2, '0');
                                        const min = String(date.getMinutes()).padStart(2, '0');
                                        const s = String(date.getSeconds()).padStart(2, '0');
                                        setWorkEndTime(`${y}-${m}-${d} ${h}:${min}:${s}`);
                                    } else {
                                        setWorkEndTime('');
                                    }
                                    setEndTimePickerVisible(false);
                                    setIsTimePickerActive(false);
                                }}
                                format="YYYY-MM-DD HH:mm:ss"
                                onVisibleChange={(visible) => {
                                    console.log('结束时间选择器 onVisibleChange:', visible);
                                    if (!visible) {
                                        setEndTimePickerVisible(false);
                                        setIsTimePickerActive(false);
                                    }
                                }}
                            />
                        </View>
                    )}
                </View>

                <WebView
                    ref={webViewRef}
                    javaScriptEnabled={true}
                    domStorageEnabled={true}
                    allowFileAccess={true}
                    mixedContentMode="compatibility"
                    onMessage={handleWebViewMessage}
                    onLoadEnd={() => webViewRef.current?.injectJavaScript('initGantt()')}
                    source={{
                        html: `
                    <!DOCTYPE html>
                    <html>
                    <head>
                        <meta charset="utf-8">
                        <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
                        <title>工单调度甘特图</title>
                        <style>
                            html, body {
                                height: 100%;
                                padding: 0px;
                                margin: 0px;
                                overflow: hidden;
                                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                            }
                            #gantt_here {
                                width: 100%;
                                height: 100%;
                            }
                            
                            /* 自定义任务颜色样式 */
                            .custom_task_color {
                                /* 任务颜色将通过JavaScript动态设置 */
                            }
                            
                            /* 甘特图任务样式优化 */
                            .gantt_task_line {
                                border-radius: 3px;
                                font-weight: 500;
                                color: #333;
                            }
                            
                            /* 资源组样式 */
                            .gantt_row.gantt_project {
                                background-color: #f8f9fa;
                                font-weight: bold;
                            }
                            
                            /* 隐藏设备本身的进度条 */
                            .gantt_task_line[data-task-id*="hide"] {
                                display: none !important;
                            }
                            
                            /* 隐藏特定类型的任务条 */
                            .hide-task .gantt_task_line {
                                display: none !important;
                            }
                            
                            /* 隐藏带有hide-task类的任务条 */
                            .hide-task {
                                display: none !important;
                            }
                            
                            /* 隐藏带有hide属性的任务条 */
                            .gantt_task_line[data-task-id*="hide"],
                            .gantt_task_line[data-task-id*="hidden"] {
                                display: none !important;
                            }
                            
                            /* 隐藏带有hide_bar属性的任务条 */
                            .gantt_task_line[data-task-id*="hide_bar"] {
                                display: none !important;
                            }
                            
                            /* 强制隐藏所有带有hide相关属性的任务条 */
                            .gantt_task_line[data-task-id*="hide"],
                            .gantt_task_line[data-task-id*="hidden"],
                            .gantt_task_line[data-task-id*="hide_bar"] {
                                display: none !important;
                                visibility: hidden !important;
                                opacity: 0 !important;
                                height: 0 !important;
                                width: 0 !important;
                            }
                            
                            /* 隐藏进度条 */
                            .gantt_progress_wrapper {
                                display: none !important;
                            }
                            
                            /* 隐藏任务条中的进度显示 */
                            .gantt_task_progress {
                                display: none !important;
                            }
                            
                            /* 隐藏进度文本 */
                            .gantt_task_progress_wrapper {
                                display: none !important;
                            }
                        </style>
                    </head>
                    <body>
                        <div id="gantt_here"></div>
                        
                        <script>
                            // 创建日志函数，同时输出到控制台和发送到React Native
                            function logToReactNative(message, level = 'log') {
                                // 输出到WebView控制台
                                console[level](message);
                                // 发送到React Native
                                if (window.ReactNativeWebView) {
                                    window.ReactNativeWebView.postMessage(JSON.stringify({
                                        type: 'log',
                                        level: level,
                                        message: message
                                    }));
                                }
                            }
                            
                            // 测试JavaScript执行
                            logToReactNative('WebView JavaScript开始执行...');
                            document.addEventListener('DOMContentLoaded', function() {
                                logToReactNative('DOM加载完成');
                            });
                            
                            // 动态加载甘特图库
                            function loadGanttLibrary() {
                                logToReactNative('开始加载甘特图JS库...');
                                var script = document.createElement('script');
                                script.src = 'file:///android_asset/components/gantt/codebase/dhtmlxgantt.js';
                                script.onload = function() {
                                    logToReactNative('甘特图JS库加载成功');
                                    loadGanttCSS();
                                };
                                script.onerror = function() {
                                    logToReactNative('甘特图JS库加载失败', 'error');
                                    showError('甘特图JS库加载失败');
                                };
                                document.head.appendChild(script);
                            }
                            
                            // 加载甘特图CSS
                            function loadGanttCSS() {
                                logToReactNative('开始加载甘特图CSS...');
                                var link = document.createElement('link');
                                link.rel = 'stylesheet';
                                link.href = 'file:///android_asset/components/gantt/codebase/dhtmlxgantt.css';
                                link.onload = function() {
                                    logToReactNative('甘特图CSS加载成功');
                                    initGanttChart();
                                };
                                link.onerror = function() {
                                    logToReactNative('甘特图CSS加载失败', 'error');
                                    showError('甘特图CSS加载失败');
                                };
                                document.head.appendChild(link);
                            }
                            
                            // 初始化甘特图
                            function initGanttChart() {
                                try {
                                    // 配置甘特图
                                    gantt.config.date_format = "%Y-%m-%d %H:%i";
                                    gantt.config.scale_height = 50;
                                    gantt.config.row_height = 40;
                                    gantt.config.min_column_width = 70;
                                    
                                    // 配置甘特图列 - 显示资源列，支持树形结构
                                    gantt.config.columns = [
                                        {name: "text", label: "资源", tree: true, align: "left", width: 250}
                                    ];
                                    
                                    // 配置甘特图任务显示
                                    gantt.config.auto_scheduling = false;
                                    gantt.config.auto_scheduling_strict = false;
                                    gantt.config.work_time = true;
                                    gantt.config.show_links = false; // 不显示任务链接线
                                    gantt.config.drag_resize = false; // 禁用拖拽调整
                                    gantt.config.drag_move = false; // 禁用拖拽移动
                                    gantt.config.drag_project = false; // 禁用项目拖拽
                                    gantt.config.drag_multiple = false; // 禁用多选拖拽
                                    gantt.config.drag_progress = false; // 禁用进度拖拽
                                    
                                    // 禁用编辑功能
                                    gantt.config.readonly = true; // 设置为只读模式
                                    gantt.config.show_quick_info = false; // 禁用快速信息提示
                                    gantt.config.show_chart = true; // 保持图表显示
                                    gantt.config.show_progress = false; // 隐藏进度条显示
                                    
                                    // 配置任务模板
                                    gantt.templates.task_text = function(start, end, task) {
                                        return task.text || '';
                                    };
                                    
                                    // 配置任务颜色和样式
                                    gantt.templates.task_class = function(start, end, task) {
                                        var className = 'custom_task_color';
                                        // 如果任务有隐藏属性，添加隐藏类
                                        if (task.hide || task.hidden || task.hide_bar) {
                                            className += ' hide-task';
                                        }
                                        // 参考PC端逻辑：如果任务没有batch_order_num，则隐藏
                                        if (!task.batch_order_num) {
                                            className += ' hide-task';
                                        }
                                        return className;
                                    };
                                    
                                    // 配置任务文本显示
                                    gantt.templates.task_text = function(start, end, task) {
                                        return task.text || '';
                                    };
                                    
                                    // 配置任务颜色
                                    gantt.templates.task_color = function(start, end, task) {
                                        return task.color || "#41bf42";
                                    };
                                    
                                    // 配置任务是否显示
                                    gantt.templates.task_height = function(start, end, task) {
                                        // 如果任务需要隐藏，返回0高度
                                        if (task.hide || task.hidden || task.hide_bar) {
                                            return 0;
                                        }
                                        return 20; // 默认任务高度
                                    };
                                    
                                    // 配置任务是否显示 - 新增函数
                                    gantt.templates.task_display = function(start, end, task) {
                                        // 如果任务需要隐藏，返回false
                                        if (task.hide || task.hidden || task.hide_bar) {
                                            return false;
                                        }
                                        return true;
                                    };
                                    
                                    // 配置工具提示文本，参考PC端逻辑
                                    gantt.templates.tooltip_text = function(start, end, task) {
                                        if (task.batch_order_num && task.mbom_num) {
                                            return '<b>工单号：</b>' + (task.work_order_num || 'N/A') +
                                                '<br/><b>批次：</b>' + task.batch_order_num +
                                                '<br/><b>产品名称：</b>' + (task.product_name || 'N/A') +
                                                '<br/><b>工序号：</b>' + task.mbom_num +
                                                '<br/><b>工艺号：</b>' + (task.process_num || 'N/A') +
                                                '<br/><b>派工设备：</b>' + (task.work_device_num || 'N/A') +
                                                '<br/><b>开始时间：</b>' + (task.work_start || 'N/A') +
                                                '<br/><b>结束时间：</b>' + (task.work_end || 'N/A');
                                        } else {
                                            return '<b>' + task.text + '</b>';
                                        }
                                    };
                                    
                                    // 添加行点击事件（左侧资源列点击）
                                    gantt.attachEvent("onRowClick", function(id) {
                                        var task = gantt.getTask(id);
                                        if (task && (task.type === 'project' || task.parent === 'room_root')) {
                                            // 发送资源详情到React Native
                                            if (window.ReactNativeWebView) {
                                                window.ReactNativeWebView.postMessage(JSON.stringify({
                                                    type: 'resourceClick',
                                                    resource: task
                                                }));
                                            }
                                            return false; // 阻止默认行为
                                        }
                                        return true; // 允许其他点击事件
                                    });
                                    
                                    // 添加任务区域点击事件（右侧甘特图区域点击）
                                    gantt.attachEvent("onTaskClick", function(id) {
                                        var task = gantt.getTask(id);
                                        if (task && task.type === 'task') {
                                            // 发送任务详情到React Native
                                            if (window.ReactNativeWebView) {
                                                window.ReactNativeWebView.postMessage(JSON.stringify({
                                                    type: 'taskClick',
                                                    task: task
                                                }));
                                            }
                                            return false; // 阻止默认行为
                                        } else if (task && (task.type === 'project' || task.parent === 'room_root')) {
                                            // 点击右侧任务区域中的资源时，也显示资源详情
                                            if (window.ReactNativeWebView) {
                                                window.ReactNativeWebView.postMessage(JSON.stringify({
                                                    type: 'resourceClick',
                                                    resource: task
                                                }));
                                            }
                                            return false; // 阻止默认行为
                                        }
                                        return true; // 允许其他点击事件
                                    });
                                    
                                    // 禁用默认的资源编辑弹窗
                                    gantt.attachEvent("onTaskDblClick", function(id) {
                                        return false; // 禁用双击编辑
                                    });
                                    
                                    // 禁用默认的任务编辑弹窗
                                    gantt.attachEvent("onLightbox", function(id) {
                                        return false; // 禁用轻量级编辑弹窗
                                    });
                                    
                                    // 禁用默认的右键菜单
                                    gantt.attachEvent("onContextMenu", function(id, e) {
                                        return false; // 禁用右键菜单
                                    });
                                    
                                    // 设置时间刻度 - 默认为小时视图
                                    gantt.config.scales = [
                                        {unit: "day", step: 1, format: "%m月%d日"},
                                        {unit: "hour", step: 1, format: "%H:00", css: function(date) {
                                            if (date.getDay() === 0 || date.getDay() === 6) {
                                                return "weekend";
                                            }
                                        }}
                                    ];
                                    
                                    // 添加周末样式
                                    gantt.templates.scale_cell_class = function(date) {
                                        if (date.getDay() === 0 || date.getDay() === 6) {
                                            return "weekend";
                                        }
                                    };
                                    
                                    // 初始化甘特图
                                    logToReactNative('开始初始化甘特图到DOM元素...');
                                    gantt.init("gantt_here");
                                    logToReactNative('甘特图初始化完成');
                                    
                                    // 设置默认时间刻度为小时视图
                                    window.currentTimeScale = 'hour';
                                    
                                    // 甘特图初始化完成，等待数据加载
                                    logToReactNative('甘特图初始化完成，等待数据加载...');
                                    
                                    // 显示空白甘特图，不显示空状态提示
                                    logToReactNative('显示空白甘特图');
                                    
                                    // 添加周末样式
                                    try {
                                        if (typeof gantt.addStyle === 'function') {
                                            gantt.addStyle({
                                                ".weekend": {
                                                    background: "#f8f9fa"
                                                }
                                            });
                                        } else {
                                            var style = document.createElement('style');
                                            style.textContent = '.weekend { background: #f8f9fa !important; }';
                                            document.head.appendChild(style);
                                        }
                                    } catch (error) {
                                        var style = document.createElement('style');
                                        style.textContent = '.weekend { background: #f8f9fa !important; }';
                                        document.head.appendChild(style);
                                    }
                                    
                                } catch (error) {
                                    logToReactNative('甘特图初始化失败: ' + error.message, 'error');
                                    showError('甘特图初始化失败: ' + error.message);
                                }
                            }
                            
                            // 显示错误信息
                            function showError(message) {
                                logToReactNative('显示错误信息: ' + message, 'error');
                                var container = document.getElementById('gantt_here');
                                container.innerHTML = '<div style="padding: 20px; text-align: center; color: red;"><h3>错误</h3><p>' + message + '</p></div>';
                            }
                            
                            // 页面加载完成后开始加载甘特图
                            logToReactNative('页面加载完成，开始初始化甘特图...');
                            logToReactNative('gantt对象状态: ' + typeof gantt);
                            
                            if (typeof gantt !== 'undefined') {
                                logToReactNative('gantt对象已存在，直接初始化...');
                                initGanttChart();
                            } else {
                                logToReactNative('gantt对象不存在，开始加载甘特图库...');
                                loadGanttLibrary();
                            }
                            
                            // 添加页面加载完成的确认
                            logToReactNative('WebView JavaScript代码已加载完成');
                            logToReactNative('消息监听器已设置');
                            
                                                        // 监听来自React Native的消息
                            logToReactNative('设置消息监听器...');
                            
                            // 创建全局函数供React Native调用
                            window.handleReactNativeMessage = function(messageData) {
                                try {
                                    logToReactNative('WebView收到React Native消息: ' + JSON.stringify(messageData));
                                    
                                    if (messageData.type === 'clearGantt') {
                                        // 清除甘特图数据
                                        if (typeof gantt !== 'undefined') {
                                            gantt.clearAll();
                                            logToReactNative('甘特图数据已清除');
                                            
                                            // 显示空白甘特图，不显示空状态提示
                                            logToReactNative('显示空白甘特图');
                                        }
                                    } else if (messageData.type === 'changeTimeScale') {
                                        // 切换时间刻度
                                        if (typeof gantt !== 'undefined') {
                                            changeGanttTimeScale(messageData.scale);
                                        }
                                    } else if (messageData.type === 'updateGanttData') {
                                        // 更新甘特图数据
                                        logToReactNative('准备更新甘特图数据，数据类型: ' + typeof messageData.data);
                                        logToReactNative('数据内容: ' + JSON.stringify(messageData.data));
                                        
                                        if (typeof gantt !== 'undefined') {
                                            updateGanttData(messageData.data);
                                            logToReactNative('甘特图数据已更新');
                                        } else {
                                            logToReactNative('gantt对象未定义，无法更新数据', 'error');
                                        }
                                    } else {
                                        logToReactNative('未知消息类型: ' + messageData.type);
                                    }
                                } catch (error) {
                                    logToReactNative('处理消息失败: ' + error.message, 'error');
                                    logToReactNative('错误详情: ' + error.stack, 'error');
                                }
                            };
                            
                            logToReactNative('全局消息处理函数已设置: window.handleReactNativeMessage');
                            
                            // 更新甘特图数据
                            function updateGanttData(apiData) {
                                try {
                                    logToReactNative('=== 开始更新甘特图数据 ===');
                                    logToReactNative('接收到API数据: ' + JSON.stringify(apiData));
                                    logToReactNative('API数据类型: ' + typeof apiData);
                                    logToReactNative('API数据是否为数组: ' + Array.isArray(apiData));
                                    
                                    // 检查数据结构
                                    if (!apiData || (!apiData.elements && !apiData.tasks)) {
                                        logToReactNative('API数据结构不正确', 'error');
                                        logToReactNative('apiData: ' + JSON.stringify(apiData));
                                        logToReactNative('apiData.elements: ' + JSON.stringify(apiData?.elements));
                                        logToReactNative('apiData.tasks: ' + JSON.stringify(apiData?.tasks));
                                        return;
                                    }
                                    
                                    // 确保甘特图容器正确显示
                                    logToReactNative('准备显示甘特图数据');
                                    
                                    var ganttData = {
                                        data: [],
                                        links: []
                                    };
                                    
                                    // 参考PC端逻辑，构建正确的数据结构
                                    // 1. 先创建车间根节点（但不立即添加）
                                    var roomItem = null;
                                    
                                    // 2. 处理elements数据 - 构建资源组层级结构，参考PC端逻辑
                                    if (apiData.elements && Array.isArray(apiData.elements)) {
                                        logToReactNative('处理elements数据，数量: ' + apiData.elements.length);
                                        logToReactNative('第一个element示例: ' + JSON.stringify(apiData.elements[0]));
                                        
                                        // 按车间分组处理
                                        var roomGroups = {};
                                        apiData.elements.forEach(function(element) {
                                            var roomId = element.room_id || 'default';
                                            if (!roomGroups[roomId]) {
                                                roomGroups[roomId] = {
                                                    room_name: element.room_name || '车间',
                                                    elements: []
                                                };
                                            }
                                            roomGroups[roomId].elements.push(element);
                                        });
                                        
                                        // 处理每个车间的数据
                                        Object.keys(roomGroups).forEach(function(roomId) {
                                            var roomData = roomGroups[roomId];
                                            var roomElements = roomData.elements;
                                            
                                            // 过滤出有子节点的资源组
                                            var validResourceGroups = roomElements.filter(function(element) {
                                                return element.label && element.children && element.children.length > 0;
                                            });
                                            
                                            logToReactNative('车间 ' + roomData.room_name + ' 有效资源组数量: ' + validResourceGroups.length);
                                            
                                            // 只有当有有效资源组时才创建车间节点
                                            if (validResourceGroups.length > 0) {
                                                // 创建车间节点 - 参考PC端，设置为隐藏进度条
                                                roomItem = {
                                                    id: 'room_root',
                                                    text: roomData.room_name, // 使用实际的车间名称
                                                    type: "project",
                                                    open: true,
                                                    parent: 0,
                                                    hide_bar: true, // 隐藏车间进度条
                                                    hide: true,
                                                    hidden: true,
                                                    class: 'hide-task',
                                                    // 参考PC端，确保没有batch_order_num属性
                                                    batch_order_num: null
                                                };
                                                ganttData.data.push(roomItem);
                                                logToReactNative('添加车间根节点: ' + JSON.stringify(roomItem));
                                                
                                                // 添加有效的资源组
                                                validResourceGroups.forEach(function(element, index) {
                                                    logToReactNative('处理有效资源组 ' + index + ': ' + JSON.stringify(element));
                                                    
                                                    var groupItem = {
                                                        id: element.id,
                                                        text: element.label,
                                                        type: "project",
                                                        open: true,
                                                        parent: 'room_root',
                                                        hide_bar: true, // 隐藏资源组进度条
                                                        hide: true,
                                                        hidden: true,
                                                        class: 'hide-task',
                                                        // 参考PC端，确保没有batch_order_num属性
                                                        batch_order_num: null
                                                    };
                                                    ganttData.data.push(groupItem);
                                                    logToReactNative('添加资源组: ' + JSON.stringify(groupItem));
                                                    
                                                    // 添加子设备 - 参考PC端，设置为隐藏进度条
                                                    element.children.forEach(function(child, childIndex) {
                                                        var deviceItem = {
                                                            id: child.id,
                                                            text: child.label,
                                                            type: "project", // 改为project类型
                                                            parent: element.id,
                                                            open: false, // 设备节点默认关闭，不展开显示任务
                                                            hide_bar: true, // 隐藏设备本身的进度条
                                                            hide: true,
                                                            hidden: true,
                                                            class: 'hide-task', // 添加CSS类
                                                            render: 'split', // 添加render属性，确保任务平铺显示
                                                            // 参考PC端，确保没有batch_order_num属性
                                                            batch_order_num: null
                                                        };
                                                        ganttData.data.push(deviceItem);
                                                        logToReactNative('添加子设备 ' + childIndex + ': ' + JSON.stringify(deviceItem));
                                                    });
                                                });
                                            } else {
                                                logToReactNative('车间 ' + roomData.room_name + ' 没有有效资源组，跳过');
                                            }
                                        });
                                    }
                                    
                                    // 3. 处理tasks数据 - 构建任务数据，使用order_color作为颜色
                                    if (apiData.tasks && Array.isArray(apiData.tasks)) {
                                        logToReactNative('处理tasks数据，数量: ' + apiData.tasks.length);
                                        logToReactNative('第一个task示例: ' + JSON.stringify(apiData.tasks[0]));
                                        
                                        // 过滤出有效的任务（有设备ID和时间）
                                        var validTasks = apiData.tasks.filter(function(task) {
                                            return task.work_device_id && task.work_start && task.work_end;
                                        });
                                        
                                        logToReactNative('有效任务数量: ' + validTasks.length);
                                        
                                        validTasks.forEach(function(task, index) {
                                            logToReactNative('处理task ' + index + ': ' + JSON.stringify(task));
                                            
                                            var taskItem = {
                                                id: 'task_' + task.id,
                                                text: task.batch_order_num + ' #' + task.mbom_num,
                                                start_date: task.work_start,
                                                end_date: task.work_end,
                                                parent: task.work_device_id, // 父级是设备ID
                                                type: "task",
                                                // 移除硬编码的进度值，让工序不显示进度条
                                                // progress: 0.5,
                                                color: task.order_color || "#41bf42",
                                                open: true, // 任务默认展开
                                                // 保存完整的任务信息用于详情显示
                                                work_order_num: task.work_order_num,
                                                batch_order_num: task.batch_order_num,
                                                product_name: task.product_name,
                                                mbom_num: task.mbom_num,
                                                process_num: task.process_num,
                                                work_device_num: task.work_device_num,
                                                work_start: task.work_start,
                                                work_end: task.work_end
                                            };
                                            ganttData.data.push(taskItem);
                                            logToReactNative('添加任务 ' + index + ': ' + JSON.stringify(taskItem));
                                        });
                                    }
                                    
                                    logToReactNative('=== 转换后的甘特图数据 ===');
                                    logToReactNative('总数据量: ' + ganttData.data.length);
                                    logToReactNative('数据内容: ' + JSON.stringify(ganttData.data));
                                    
                                    // 验证数据结构
                                    var roomCount = 0, groupCount = 0, deviceCount = 0, taskCount = 0;
                                    ganttData.data.forEach(function(item) {
                                        if (item.parent === 0) roomCount++;
                                        else if (item.parent === 'room_root') groupCount++;
                                        else if (item.type === 'project' && item.hide_bar) deviceCount++;
                                        else if (item.type === 'task') taskCount++;
                                    });
                                    logToReactNative('数据结构统计: 车间=' + roomCount + ', 资源组=' + groupCount + ', 设备=' + deviceCount + ', 任务=' + taskCount);
                                    
                                    // 清除现有数据并加载新数据
                                    logToReactNative('清除现有甘特图数据...');
                                    gantt.clearAll();
                                    
                                    logToReactNative('解析新数据到甘特图...');
                                    gantt.parse(ganttData);
                                    
                                    // 动态设置任务颜色
                                    setTimeout(function() {
                                        ganttData.data.forEach(function(item) {
                                            if (item.type === 'task' && item.color) {
                                                var domElement = gantt.getTaskNode(item.id);
                                                if (domElement) {
                                                    domElement.style.backgroundColor = item.color;
                                                    domElement.style.borderColor = item.color;
                                                    logToReactNative('设置任务 ' + item.id + ' 颜色为: ' + item.color);
                                                }
                                            }
                                        });
                                        
                                        // 强制隐藏所有需要隐藏的任务条
                                        ganttData.data.forEach(function(item) {
                                            if (item.hide || item.hidden || item.hide_bar) {
                                                var domElement = gantt.getTaskNode(item.id);
                                                if (domElement) {
                                                    domElement.style.display = 'none';
                                                    domElement.style.visibility = 'hidden';
                                                    domElement.style.opacity = '0';
                                                    domElement.style.height = '0';
                                                    domElement.style.width = '0';
                                                    logToReactNative('强制隐藏任务条: ' + item.id);
                                                }
                                            }
                                        });
                                        
                                        // 强制隐藏所有进度条
                                        var progressElements = document.querySelectorAll('.gantt_progress_wrapper, .gantt_task_progress, .gantt_task_progress_wrapper');
                                        progressElements.forEach(function(element) {
                                            element.style.display = 'none';
                                            element.style.visibility = 'hidden';
                                            element.style.opacity = '0';
                                            logToReactNative('强制隐藏进度条元素');
                                        });
                                        
                                        // 重新应用当前选择的时间刻度
                                        if (window.currentTimeScale) {
                                            logToReactNative('重新应用时间刻度: ' + window.currentTimeScale);
                                            changeGanttTimeScale(window.currentTimeScale);
                                        }
                                    }, 100);
                                    
                                    logToReactNative('甘特图数据更新完成，数据量: ' + ganttData.data.length);
                                    logToReactNative('甘特图当前任务数量: ' + gantt.getTaskByTime().length);
                                } catch (error) {
                                    logToReactNative('更新甘特图数据失败: ' + error.message, 'error');
                                    logToReactNative('错误详情: ' + error.stack, 'error');
                                }
                            }
                            
                            // 切换甘特图时间刻度
                            function changeGanttTimeScale(scale) {
                                // 保存当前选择的时间刻度到全局变量
                                window.currentTimeScale = scale;
                                
                                var scales = [];
                                
                                switch(scale) {
                                    case 'hour':
                                        scales = [
                                            {unit: "day", step: 1, format: "%m月%d日"},
                                            {unit: "hour", step: 1, format: "%H:00"}
                                        ];
                                        break;
                                    case 'day':
                                        scales = [
                                            {unit: "month", step: 1, format: "%Y年%m月"},
                                            {unit: "day", step: 1, format: "%j"}
                                        ];
                                        break;
                                    case 'week':
                                        scales = [
                                            {unit: "month", step: 1, format: "%Y年%m月"},
                                            {unit: "week", step: 1, format: "第%W周"}
                                        ];
                                        break;
                                    case 'month':
                                        scales = [
                                            {unit: "year", step: 1, format: "%Y年"},
                                            {unit: "month", step: 1, format: "%m月"}
                                        ];
                                        break;
                                    case 'quarter':
                                        scales = [
                                            {unit: "year", step: 1, format: "%Y年"},
                                            {unit: "quarter", step: 1, format: "Q%q"}
                                        ];
                                        break;
                                    case 'year':
                                        scales = [
                                            {unit: "year", step: 1, format: "%Y年"}
                                        ];
                                        break;
                                    default:
                                        scales = [
                                            {unit: "month", step: 1, format: "%Y年%m月"},
                                            {unit: "day", step: "%j"}
                                        ];
                                }
                                
                                gantt.config.scales = scales;
                                gantt.render();
                                logToReactNative('时间刻度已切换到: ' + scale);
                            }
                        </script>
                    </body>
                    </html>
                `}}
                    style={styles.webview}
                    startInLoadingState={true}
                    scalesPageToFit={true}
                    onError={(syntheticEvent) => {
                        const { nativeEvent } = syntheticEvent;
                        console.warn('WebView error: ', nativeEvent);
                    }}
                    onHttpError={(syntheticEvent) => {
                        const { nativeEvent } = syntheticEvent;
                        console.warn('WebView HTTP error: ', nativeEvent);
                    }}
                />
            </View>
        </SafeAreaView>
    );
}   